package com.absorbx.commons;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.log4j.Logger;
import org.springframework.security.context.SecurityContextHolder;

import com.absorbx.security.User;


public class Utils {
	final static Logger logger = Logger.getLogger(Utils.class);
	public static final String DATE_FMT = "yyyy-MM-dd";

	/* replace multiple whitespaces between words with single blank */
	public static String str(List<String> list) {
		StringBuilder sbr = new StringBuilder();
		for (String color : list) {
			sbr.append(color + ",");

		}
		return sbr.toString();
	}

	public static List<String> split(String str) {
		String[] array = str.split(",");

		return Arrays.asList(array);
	}

	public static String regexReplace(String source, String patternString,
			String replacementString, String suffix) {
		// Compile regular expression
		Pattern pattern = Pattern.compile(patternString);

		// Replace all occurrences of pattern in input
		Matcher matcher = pattern.matcher(source);
		String replacedString = matcher.replaceAll(replacementString);
		return replacedString + suffix;
	}

	public static User getUser() {
		User user = null;
		Object obj = SecurityContextHolder.getContext().getAuthentication()
				.getPrincipal();
		if (obj instanceof User) {
			user = (User) obj;
		}
		return user;
	}

	/**
	 * get the
	 * 
	 * @param date
	 * @param formatPattern
	 * @return
	 */
	public static String[] weekDate(Date date, String formatPattern) {
		String[] range = new String[2];
		Calendar cal = Calendar.getInstance();
		cal.setTime(date);
		cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
		SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);

		range[0] = sdf.format(cal.getTime());
		cal.set(Calendar.DAY_OF_WEEK, Calendar.FRIDAY);
		range[1] = sdf.format(cal.getTime());
		return range;

	}

	public static String[] monthDate(Date date, String formatPattern) {
		String[] range = new String[2];
		SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
		Calendar cal = Calendar.getInstance();
		cal.set(Calendar.DAY_OF_MONTH, 1);
		range[0] = sdf.format(cal.getTime());
		System.out.println(range[0]);
		cal.set(Calendar.DAY_OF_MONTH, cal
				.getActualMaximum(Calendar.DAY_OF_MONTH));
		range[1] = sdf.format(cal.getTime());
		System.out.println(range[1]);
		return range;

	}

	public static String nominizeString(String orginal) {
		String nominized = orginal.replaceAll("[^a-zA-Z0-9]", "");
		return nominized;
	}

	public static Date parseDate(String source, String formatPattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(formatPattern);
		Date date = null;
		try {
			date = sdf.parse(source);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		return date;
	}
}
